<template>
    <div class="tech-container">
        <!-- Global Header -->
        <global-header />

        <!-- Futuristic Background Elements -->
        <div class="tech-grid"></div>
        <div class="data-lines"></div>
        <div class="data-dashboard-circles"></div>
        <div class="rotating-gear top-left"></div>
        <div class="rotating-gear bottom-right"></div>

        <!-- Digital data streams -->
        <div class="binary-stream stream-1"></div>
        <div class="binary-stream stream-2"></div>

        <!-- 流星特效 -->
        <div class="meteor meteor-1"></div>
        <div class="meteor meteor-2"></div>
        <div class="meteor meteor-3"></div>

        <!-- Holographic scanner effect -->
        <div class="scan-line"></div>

        <!-- Main content wrapper with register box -->
        <div class="content-wrapper">
            <!-- Cyberpunk-style register box -->
            <div class="tech-box">
                <div class="cyberpunk-corner top-left"></div>
                <div class="cyberpunk-corner top-right"></div>
                <div class="cyberpunk-corner bottom-left"></div>
                <div class="cyberpunk-corner bottom-right"></div>

                <div class="tech-header">
                    <h1 class="title">DevOps自动化运维系统</h1>
                    <div class="tech-line"></div>
                </div>

                <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form" @submit.prevent="handleRegister">
                    <el-form-item prop="username">
                        <el-input v-model="registerForm.username" placeholder="用户名" class="tech-input">
                            <template #prefix>
                                <i class="fa fa-user"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="email">
                        <el-input v-model="registerForm.email" placeholder="邮箱" class="tech-input">
                            <template #prefix>
                                <i class="fa fa-envelope"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input v-model="registerForm.password" type="password" placeholder="密码" class="tech-input">
                            <template #prefix>
                                <i class="fa fa-lock"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="password_confirm">
                        <el-input v-model="registerForm.password_confirm" type="password" placeholder="确认密码" class="tech-input">
                            <template #prefix>
                                <i class="fa fa-lock"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="first_name">
                        <el-input v-model="registerForm.first_name" placeholder="名字" class="tech-input">
                            <template #prefix>
                                <i class="fa fa-id-card"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="last_name">
                        <el-input v-model="registerForm.last_name" placeholder="姓氏" class="tech-input" @keyup.enter="handleRegister">
                            <template #prefix>
                                <i class="fa fa-id-card"></i>
                            </template>
                        </el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" :loading="loading" class="tech-button" @click="handleRegister">
                            <span class="btn-text">注册账号</span>
                            <span class="btn-glitch"></span>
                        </el-button>
                    </el-form-item>

                    <div class="tech-link">
                        已有账号? <a @click="goToLogin">立即登录</a>
                    </div>
                </el-form>

                <div class="tech-circles">
                    <div class="circle"></div>
                    <div class="circle"></div>
                    <div class="circle"></div>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <app-footer class="register-footer" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import AppFooter from '@/components/Footer.vue'
import GlobalHeader from '@/components/GlobalHeader.vue'

const router = useRouter()
const store = useAppStore()

const registerFormRef = ref<FormInstance>()
const loading = ref(false)

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  password_confirm: '',
  first_name: '',
  last_name: ''
})

// 密码确认验证
const validatePasswordConfirm = (rule: any, value: string, callback: Function) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  password_confirm: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePasswordConfirm, trigger: 'blur' }
  ],
  first_name: [
    { required: false, max: 30, message: '名字不能超过30个字符', trigger: 'blur' }
  ],
  last_name: [
    { required: false, max: 30, message: '姓氏不能超过30个字符', trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      store.register(registerForm)
        .then(() => {
          ElMessage.success('注册成功！即将跳转到登录页面')
          setTimeout(() => {
            router.push('/login')
          }, 1500)
          loading.value = false
        })
        .catch(error => {
          let errorMessage = '注册失败，请检查注册信息'
          if (error.response && error.response.data) {
            const errors = error.response.data
            if (typeof errors === 'object') {
              const messages = []
              for (const field in errors) {
                if (Array.isArray(errors[field])) {
                  messages.push(`${field}: ${errors[field].join(', ')}`)
                } else {
                  messages.push(`${field}: ${errors[field]}`)
                }
              }
              errorMessage = messages.join('\n')
            } else if (typeof errors === 'string') {
              errorMessage = errors
            }
          }
          ElMessage.error(errorMessage)
          loading.value = false
        })
    }
  })
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
@use '../styles/tech-background.scss';

.tech-container {
    /* Setup flex column layout to handle footer correctly */
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    /* Add padding-top to accommodate global header */
    padding-top: 40px;
    box-sizing: border-box;
    position: relative;
}

.content-wrapper {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    padding: 20px 0;
    margin-bottom: 60px; /* Space for footer */
}

.register-form {
    width: 100%;
}

.register-footer {
    position: relative;
    width: 100%;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
    margin-top: auto; /* Push to bottom of flex container */
}

@media screen and (max-height: 700px) {
    /* For very small screens, adjust the footer position */
    .content-wrapper {
        padding-top: 10px;
        padding-bottom: 10px;
        margin-bottom: 40px;
    }

    .tech-box {
        padding: 20px;
    }

    .tech-header {
        margin-bottom: 15px;
    }
}
</style>
